package com.pet.server.ext.service;

import java.util.Date;
import java.util.List;

import com.pet.server.ext.ApiError;

import com.pet.server.ext.constants.BaseAttribute;
import com.pet.server.ext.data.Constant;
import com.pet.server.ext.data.ConstantUi;
import com.pet.server.ext.data.VerificationCode;
import com.pet.server.ext.dbutil.JdbcTemplate;
import com.pet.server.ext.dbutil.Sql;
import com.pet.server.ext.util.DateUtil;


public class SystemService {
	private JdbcTemplate jdbcTemplate = new JdbcTemplate();

	
	public List<Constant> queryConstant(String pcode) throws ApiError{
		Sql sql = new Sql("SELECT c.* FROM constant c WHERE c.pcode=? and c.display=?");
		    sql.addParam(pcode,BaseAttribute.LOGIC_TRUE);
		    
		    sql.append(" order by c.sort DESC");
		    return jdbcTemplate.queryForList(sql, Constant.class);
	}
	
	public List<Constant> queryConstant() throws ApiError{
		Sql sql = new Sql("SELECT c.* FROM constant c WHERE c.display=?");
		    sql.addParam(BaseAttribute.LOGIC_TRUE);
		    sql.append(" order by c.sort DESC");
		    return jdbcTemplate.queryForList(sql, Constant.class);
	}
	
	public List<ConstantUi> queryConstantUi(String pcode) throws ApiError{
		Sql sql = new Sql("SELECT c.* FROM constant_ui c WHERE 1=1");
		    sql.append("and", "c.pcode","=", pcode);
		    return jdbcTemplate.queryForList(sql, ConstantUi.class);
	}
	
	//INSERT INTO verification_code (phone_number, verification_code) VALUES (?,?)
	public VerificationCode saveVerification(VerificationCode vcode) throws ApiError{
		Sql sql = new Sql("INSERT INTO verification_code (phone_number, verification_code) VALUES (?,?)");
		    sql.addParam(vcode.phone_number,vcode.verification_code);
		    vcode.id=jdbcTemplate.saveObject(sql);
	    return vcode;	    
	}
	public Integer sendTimes(String phone_number,Date date) throws ApiError{
		Sql sql = new Sql("SELECT COUNT(1) FROM verification_code vc WHERE vc.phone_number=?");
		    sql.addParam(phone_number);
		    sql.appendBetween("AND", "vc.send_time", DateUtil.get00HourDate(date), DateUtil.get24HourDate(date));
		return jdbcTemplate.findCount(sql); 
	}
	public VerificationCode findVerification(String phone_number) throws ApiError{
		Sql sql = new Sql("SELECT vc.* FROM verification_code vc WHERE vc.phone_number=? ORDER BY vc.id DESC LIMIT 1");
	        sql.addParam(phone_number);
	    return jdbcTemplate.findObject(sql, VerificationCode.class);
	}
	public void updateVerification(Integer id) throws ApiError{
		Sql sql = new Sql("UPDATE verification_code vc SET vc.is_verified=? WHERE vc.id=?");
		    sql.addParam(BaseAttribute.LOGIC_TRUE,id);
		    jdbcTemplate.updateObject(sql);
	}
	
}
